package com.tensquare.encrypt.service;


import com.tensquare.encrypt.rsa.Base64Utils;
import com.tensquare.encrypt.rsa.RSA;
import com.tensquare.encrypt.rsa.RsaKeys;
import org.springframework.stereotype.Service;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;



/**
 * RSA 加解密
 * @author Administrator
 */
@Service("RsaService")
public class RsaServiceImpl implements RsaService {

    /***
     * RSA解密
     *
     * @param encryptData
     * @return
     * @throws Exception
     */
    public String rsaDecryptDataPEM(String encryptData, String prvKey) throws Exception {
    	byte[] encryptBytes = encryptData.getBytes();
        byte[] prvdata = RSA.decryptByPrivateKey(Base64Utils.decode(encryptData), prvKey);

        String outString = new String(prvdata, "UTF-8");
        return outString;
    }
    
    @Override
	public String rsaDecryptDataBytes(byte[] encryptBytes, String prvKey)
			throws Exception {
		// TODO Auto-generated method stub
    	byte[] prvdata = RSA.decryptByPrivateKey(encryptBytes, prvKey);
        String outString = new String(prvdata, "utf-8");
        return outString;
	}

    /***
     * RSA加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public String rsaEncryptDataPEM(String data, String pubKey) throws Exception {

        byte[] pubdata = RSA.encryptByPublicKey(data.getBytes("UTF-8"), pubKey);
        String outString = new String(Base64Utils.encode(pubdata));

        return outString;
    }

	@Override
	public String getRsaAlgorithm() {
		// TODO Auto-generated method stub
		KeyFactory keyFactory = null;
		try {
			keyFactory = KeyFactory.getInstance("RSA");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return keyFactory.getAlgorithm();
	}

    public static void main(String[] args) throws Exception {
        // 要加密的内容
        //String request = "{\n" +
        //    "\t\"userid\":\"10086\",\n" +
        //    "\t\"title\": \"我上等威风，显现一身虎胆\",\n" +
        //    "\t\"content\": \"八目共赏，赏花赏月赏秋香\",\n" +
        //    "\t\"channelid\": \"web\",\n" +
        //    "\t\"type\": \"0\"\n" +
        //    "}";
        RsaServiceImpl rsa = new RsaServiceImpl();
        // 加密
        //System.out.println( rsa.rsaEncryptDataPEM(request, RsaKeys.getServerPubKey()));

        String encrypted="Tokxa6P2pTTj/Ko0/cKYOVeVzLM462NUqfnhwyCMW8Q7wk+lxGNo7Zs6GonlIOVdaVjSaVu2LD2ykMmWTd8198wNIaiZLbP9jt+xzEJXtlITLMuR9wXdO0ZBs03+GloOxfjVvkdfxBcJ8D4bcF5UQ8GCcY39O47iYp/UrtoeR6SzEqrYE9X95TCacQVwCxrwkdQnPyEv1s7wSyeD2lx7adiJyqEHPVQKhio6pnAhxfWXsuZux7deiiSeIu2hhPeU10ldPjRvxCyxyxNGUNsrK71d65s8A91t5QSvQRUwpq8NjbEokDqNOrYnSkEtxbzaF7bjFIaOgy5aKoacWc3lEQ==";
        // 密文解密
        System.out.print(rsa.rsaDecryptDataPEM(encrypted, RsaKeys.getServerPrvKeyPkcs8()));

    }

	
}
